package com.yuerlive.rainbow.module.playlive;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.github.faucamp.simplertmp.RtmpHandler;
import com.google.gson.Gson;
import com.mrd.mina.MinaHelper;
import com.seu.magicfilter.utils.MagicFilterType;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UmengTool;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yuerlive.rainbow.API;
import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.base.BaseActivity;
import com.yuerlive.rainbow.entity.BaseData;
import com.yuerlive.rainbow.entity.EditedInfo;
import com.yuerlive.rainbow.entity.GameInfo;
import com.yuerlive.rainbow.entity.KaiboData;
import com.yuerlive.rainbow.entity.ShareInfo;
import com.yuerlive.rainbow.entity.StreamData;
import com.yuerlive.rainbow.entity.User;
import com.yuerlive.rainbow.module.live.LiveRoomActivity;
import com.yuerlive.rainbow.module.live.fragment.FragmentLayer;
import com.yuerlive.rainbow.module.playlive.adapter.GameListAdapter;
import com.yuerlive.rainbow.module.playlive.presenter.PlayLiveRoomContract;
import com.yuerlive.rainbow.module.playlive.presenter.PlayLiveRoomPresenter;
import com.yuerlive.rainbow.observer.Observerable;
import com.yuerlive.rainbow.observer.ObserverableType;
import com.yuerlive.rainbow.utils.FileUploadUtil;
import com.yuerlive.rainbow.utils.FileUtil;
import com.yuerlive.rainbow.utils.GlideUtil;
import com.yuerlive.rainbow.utils.L;
import com.yuerlive.rainbow.utils.ShareUtils;
import com.yuerlive.rainbow.utils.UserProxy;
import com.yuerlive.rainbow.widget.CustomBottomSheetDialog;
import com.yuerlive.rainbow.widget.CustomDialog;
import com.yuerlive.rainbow.widget.HorizontalListView;
import com.yuerlive.rainbow.widget.timeselector.TextUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;
import pushengine.YuerCameraView;
import pushengine.YuerPublisher;

/**
 * Created by Admin on 2017/5/23.
 */

public class PlayLiveRoomActivity extends BaseActivity<PlayLiveRoomContract.Presenter> implements PlayLiveRoomContract.View, Observerable.ISubscribe, YuerPublisher.YuerPublisherListener {
    @BindView(R.id.glsurfaceview_camera)
    YuerCameraView glCameraView;
    @BindView(R.id.ivBeauty)
    ImageView ivBeauty;
    @BindView(R.id.ivCamera)
    ImageView ivCamera;
    @BindView(R.id.ivClose)
    ImageView ivClose;
    @BindView(R.id.iv_cv_img_activity)
    ImageView ivCvImgActivity;
    @BindView(R.id.cv_img_activity)
    CardView cvImgActivity;
    @BindView(R.id.ivSina)
    ImageView ivSina;
    @BindView(R.id.ivWeixin)
    ImageView ivWeixin;
    @BindView(R.id.ivWeixinCircle)
    ImageView ivWeixinCircle;
    @BindView(R.id.ivQQ)
    ImageView ivQQ;
    @BindView(R.id.tvPlayLiveBtn)
    TextView tvPlayLiveBtn;
    @BindView(R.id.llSettingPage)
    LinearLayout llSettingPage;
    @BindView(R.id.lvGame)
    HorizontalListView lvGame;
    GameListAdapter gameListAdapter;
    @BindView(R.id.llShare)
    LinearLayout llShare;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindString(R.string.game_running)
    String gameRunning;
    int shareIndex = -1;
    private YuerPublisher mPublisher;
    private String rtmpUrl;
    private ShareInfo info;
    private BottomSheetDialog bottomSheetDialog;
    private String filename; // 图片名称
    private File outputImage;
    private static final int REQUEST_TAKE_PHOTO = 3;
    private static final int REQUEST_CROP_PHOTO = 4;
    private HashMap<String, String> params = new HashMap<>();
    private int isRunning;

    private FragmentLayer fragmentLayer;
    private int gameID;
    private static final String STOP_LIVE = "com.yuerlive.rainbow.stoplive";

    private CustomDialog exitDialog;
    private boolean isStarted;
    private boolean isShare;
    private long startTime;
    CustomDialog dialog;
    private List<GameInfo> games;
    private boolean disabled;
    private EditedInfo editInfo;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FileUploadUtil.SUCCESS:
                    try {
                        Bundle resultData = msg.getData();
                        String result = resultData.getString("result");
                        JSONObject object = new JSONObject(result);
                        if (!TextUtils.isEmpty(object.getString("object").toString())) {
                            String imgName = object.getString("object").toString();
                            editInfo = new EditedInfo();
                            editInfo.setIcon(imgName);
                            User user = UserProxy.getUser();
                            user.getUserInfo().setLiveIcon(editInfo.getIcon());
                            UserProxy.setUser(user);
                            GlideUtil.load(PlayLiveRoomActivity.this, editInfo.getIcon(), ivCvImgActivity);
                            presenter.setLiveIcon(editInfo.getIcon());
                        } else {
                            showSnackbar(getRootView(mActivity), "上传失败", 0);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case FileUploadUtil.FAILED:
                    showSnackbar(getRootView(mActivity), "上传失败", 0);
                    break;
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_play_live;
    }

    private StopLiveReceiver receiver;
    private boolean isClosed;

    @Override
    protected void initViews() {
        getWindow().addFlags(WindowManager.LayoutParams.
                FLAG_KEEP_SCREEN_ON);
        presenter = new PlayLiveRoomPresenter(this);
        presenter.startLive();
        presenter.getGameList();
        int mVideoEncodeQuality = YuerPublisher.YuerVideoEncodeQuality.VIDEO_ENCODE_QUALITY_LOW;
        mPublisher = new YuerPublisher(mVideoEncodeQuality);
        if (mPublisher != null) {
			float mScreenRatio = getScreenRatio();
            mPublisher.setCameraParameter(glCameraView,mScreenRatio);
            mPublisher.setListener(this);
            mPublisher.startCamera();
        }
        initExitDialog();
        User user = UserProxy.getUser();
        String cover = user.getUserInfo().getLiveIcon();
        if (TextUtil.isEmpty(cover)) {
            cover = user.getUserInfo().getIcon();
        }
        GlideUtil.load(this, cover, ivCvImgActivity);
        Observerable.getInstance().subscribe(ObserverableType.SHARE, this);
        receiver = new StopLiveReceiver(this);
        IntentFilter filter = new IntentFilter(STOP_LIVE);
        registerReceiver(receiver, filter);
    }

    private void initShareInfo(KaiboData data) {
        info = new ShareInfo();
        String url = data.getUrl();
        if (!url.startsWith("http")) {
            url = "http://" + url;
        }
        info.setWebUrl(url);
        info.setContent(data.getContent());
        info.setTitle(data.getTitle());
        info.setThumb(R.drawable.default_img);
        User user = UserProxy.getUser();
        String shareImage = user.getUserInfo().getLiveIcon();
        if (TextUtil.isEmpty(shareImage)) {
            shareImage = user.getUserInfo().getIcon();
        }
        info.setShareImageUrl(shareImage);
    }

    public ShareInfo getShareInfo() {
        return info;
    }

    /*切换摄像头*/
    public void switchCamera() {
        mPublisher.switchCameraFace((mPublisher.getCamraId() + 1) % Camera.getNumberOfCameras());
    }

    private boolean beautyOpen = true;

    /*打开关闭美颜*/
    public void openOrCloseBeauty() {
        if (mPublisher != null) {
            if (!beautyOpen) {
                mPublisher.switchCameraFilter(MagicFilterType.BEAUTY);
                ivBeauty.setImageResource(R.drawable.icon_beauty);
                beautyOpen = true;
            } else {
                mPublisher.switchCameraFilter(MagicFilterType.NONE);
                beautyOpen = false;
                ivBeauty.setImageResource(R.drawable.icon_beauty_close);
            }
        }
    }

    public boolean getBeautyState() {
        return beautyOpen;
    }

    @OnClick({R.id.ivCamera, R.id.ivClose, R.id.ivBeauty, R.id.iv_cv_img_activity, R.id.ivSina, R.id.ivWeixin
            , R.id.ivWeixinCircle, R.id.ivQQ, R.id.tvPlayLiveBtn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivCamera:
                switchCamera();
                break;
            case R.id.ivClose:
                stopLive();
                onBackPressed();
                break;
            case R.id.ivBeauty:
                openOrCloseBeauty();
                break;
            case R.id.iv_cv_img_activity:
                showOrHiddenBottomSheetDialog();
                break;
            case R.id.ivSina:
                shareIndex = 0;
                setSelected(0);
                break;
            case R.id.ivWeixin:
                shareIndex = 1;
                setSelected(1);
                break;
            case R.id.ivWeixinCircle:
                shareIndex = 2;
                setSelected(2);
                break;
            case R.id.ivQQ:
                shareIndex = 3;
                setSelected(3);
                break;
            case R.id.tvPlayLiveBtn:
//                startLive();
                if (disabled) {
                    showDialog();
                    return;
                }
                share(shareIndex);
                if (shareIndex == -1) {
                    startLive();
                }
                break;
        }
    }

    private void showOrHiddenBottomSheetDialog() {
        if (bottomSheetDialog == null) {
            CustomBottomSheetDialog dialog = new CustomBottomSheetDialog(this);
            View contentView = View.inflate(this, R.layout.bottom_sheet_dilaog, null);
            bottomSheetDialog = dialog.getInstance(contentView);
            contentView.findViewById(R.id.tvOpenPhoto).setOnClickListener(clickListener);
            contentView.findViewById(R.id.tvOpenPhoto).setVisibility(View.GONE);
            contentView.findViewById(R.id.tvOpenPictrue).setOnClickListener(clickListener);
            contentView.findViewById(R.id.tvCancle).setOnClickListener(clickListener);

        }
        bottomSheetDialog.show();
    }

    View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tvOpenPhoto:
                    getPicFromCamera();
                    break;
                case R.id.tvOpenPictrue:
                    takeAlbum();
                    break;
            }
            if (bottomSheetDialog != null && bottomSheetDialog.isShowing()) {
                bottomSheetDialog.dismiss();
            }
        }
    };

    private void takeAlbum() {
        Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
        getAlbum.setType("image/*");
        startActivityForResult(getAlbum, 5);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopLive();
        MinaHelper.getInstance().removeAll();
        exitDialog.dismiss();
        if (dialog != null) dialog.dismiss();
        Observerable.getInstance().unSubscribe(ObserverableType.SHARE, this);
        unregisterReceiver(receiver);
    }

    private void startImageCrop(Uri mUri) {
        Intent intent = new Intent("com.android.camera.action.CROP"); // 剪裁
        intent.setDataAndType(mUri, "image/*");
        intent.putExtra("scale", true);
        // 设置宽高比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 设置裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);

        // 广播刷新相册
        Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intentBc.setData(mUri);
        this.sendBroadcast(intentBc);
        startActivityForResult(intent, REQUEST_CROP_PHOTO); // 设置裁剪参数显示图片至ImageView
    }

    private void getPicFromCamera() {
        // 图片名称 时间命名
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        filename = format.format(date);
        // 创建File对象用于存储拍照的图片 SD卡根目录
        // 存储至DCIM文件夹
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        outputImage = new File(path, filename + ".jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (mPublisher != null) {
            boolean mResult = mPublisher.takePicture(outputImage.getAbsolutePath());
            if (mResult == true) {
                Uri imageUri = Uri.fromFile(outputImage);
                startImageCrop(imageUri);
            } else {
                L.e(TAG, "take picture failed");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (fragmentLayer != null) {
            return;
        }
        if (requestCode == REQUEST_CROP_PHOTO && resultCode == RESULT_OK) {

            L.e(TAG, "RESULT_OK");
            if (data != null && data.getExtras() != null) {
                Bitmap b = (Bitmap) data.getExtras().get("data");
                if (b != null) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                    Date date = new Date(System.currentTimeMillis());
                    filename = format.format(date);
                    // 创建File对象用于存储拍照的图片 SD卡根目录
                    // 存储至DCIM文件夹
                    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                    outputImage = new File(path, filename + ".jpg");
                    try {
                        if (outputImage.exists()) {
                            outputImage.delete();
                        }
                        outputImage.createNewFile();
                        L.e(TAG, "RESULT_OK" + outputImage);
                        b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(outputImage));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            uploadUserHead();
        } else if (requestCode == 5) {
            if (data != null) {
                startPhotoZoom(data);
            }
        }
    }

    private void startPhotoZoom(Intent data) {
        Uri uri = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            //这里如果是false，就是旧版本的uri
            if (DocumentsContract.isDocumentUri(this, data.getData())) {
                String path = FileUtil.getPath(this, data.getData());
                uri = FileUtil.pathToUri(path);
            }else {
                uri = data.getData();
            }
        } else {
            String path = FileUtil.selectImage(this, data);
            uri = FileUtil.pathToUri(path);
        }

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, 4);
        // overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    private void uploadUserHead() {
        params.clear();
        final Map<String, String> fileParams = new HashMap<>();
        fileParams.put("pic", outputImage.getAbsolutePath());
        new Thread(() -> {
            //上传剪切后的照片
            FileUploadUtil.uploadImageFile(API.HOST + API.UPLOAD_PIC, params, fileParams, mHandler);

        }).start();
    }

    private void stopLive() {
        if (!isStarted) {
            return;
        }
        if (mPublisher != null) {
            mPublisher.stopPublish();
            mPublisher = null;
        }
        isStarted = false;
    }

    private void startLive() {
        if (isStarted) {
            return;
        }
        if (mPublisher != null) {
            mPublisher.startPublish(rtmpUrl);
        }
        if (tvPlayLiveBtn != null)
            tvPlayLiveBtn.setEnabled(false);
        llSettingPage.setVisibility(View.GONE);
        isStarted = true;
        Bundle data = new Bundle();
        data.putString("chatroomId", UserProxy.getUser().getUserInfo().getChatRoomId());
        data.putInt("gameID", gameID);
        fragmentLayer = FragmentLayer.newInstance(data);
        fragmentLayer.setArguments(data);

        getSupportFragmentManager().beginTransaction().add(R.id.fragment_content, fragmentLayer)
                .show(fragmentLayer).commit();

        //isRecording = !isRecording;
        mHandler.postDelayed(() -> {
            fragmentLayer.setLiveDetail(null);
            presenter.liveNotify(gameID + "");
        }, 2000);
        startTime = System.currentTimeMillis();
    }

    private float getScreenRatio() {
        Point screenSize = new Point();
        getWindowManager().getDefaultDisplay().getSize(screenSize);
		float ratio = (float)screenSize.y/screenSize.x;
		return ratio;
    }


    @Override
    public void setPresenter(PlayLiveRoomContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void stremDataReturn(BaseData<KaiboData> data) {
        StreamData stream = new Gson().fromJson(data.getObject().getStream(), StreamData.class);
        disabled = stream.getDisabled();
        rtmpUrl = "rtmp://"
                + stream.getHosts().getPublish().getRtmp()
                + "/"
                + stream.getHub()
                + "/"
                + stream.getTitle()
                + "?key="
                + stream.getPublishKey();
        initShareInfo(data.getObject());
        isRunning = data.getObject().getIsRunning();
        gameID = data.getObject().getGameId();
        if (isRunning == 1 && gameID != 0) {
            tvTitle.setText(gameRunning);
            filterGameList(games);
        } else {
            gameID = 0;
        }

    }

    @Override
    public void showGameList(List<GameInfo> object) {
        GameInfo gameInfo = new GameInfo();
        gameInfo.setName("更多游戏");
        gameInfo.setId(-1);
        object.add(gameInfo);
        games = object;
        filterGameList(games);
        gameListAdapter = new GameListAdapter(games, mActivity, true);
        lvGame.setAdapter(gameListAdapter);
        lvGame.setOnItemClickListener((parent, v, p, id) -> {
            if (p == object.size() - 1) return;
            GameInfo game = object.get(p);
            if (isRunning == 1 && gameID != 0) {

            } else {
                if (game.isSelected()) {
                    game.setSelected(false);
                    gameID = 0;
                    gameListAdapter.notifyDataSetChanged();
                } else {
                    gameID = game.getId();
                    filterGameList(object);
                    gameListAdapter.notifyDataSetChanged();
                }
            }
        });

    }

    private void filterGameList(List<GameInfo> gameList) {
        if (gameList == null) return;
        for (GameInfo gameInfo : gameList) {
            if (gameInfo.getId() == gameID) {
                gameInfo.setSelected(true);
                continue;
            }
            gameInfo.setSelected(false);
        }
    }

    @Override
    public void startLiveFaild(int code, String result) {
        showSnackbar(getRootView(mActivity), result, 0);
    }

    @Override
    public void onBackPressed() {
        if (isStarted) {
            if (!exitDialog.isShowing()) {
                exitDialog.show();
            } else {
                exitDialog.hide();
            }
        } else {
            super.onBackPressed();
        }

    }

    /*初始化退出询问dialog*/

    private void initExitDialog() {
        if (exitDialog == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.layout_choose_dialog, null);
            exitDialog = new CustomDialog(this, view);
            TextView tvTitle = (TextView) view.findViewById(R.id.tvTitle);
            TextView tvContent = (TextView) view.findViewById(R.id.tvContent);
            tvTitle.setText("温馨提示");
            tvContent.setText("是否要退出直播间并结束直播？");
            TextView cancel = (TextView) view.findViewById(R.id.btnCancel);
            cancel.setText("否");
            cancel.setOnClickListener((v) -> {
                exitDialog.hide();
            });
            TextView tvSure = (TextView) view.findViewById(R.id.btnSure);
            tvSure.setText("是");
            tvSure.setOnClickListener((v) -> {
                isClosed = true;
                exitDialog.dismiss();
                finish();
                Intent intent = new Intent();
                intent.setClass(this, LiveEndActivity.class);
                intent.putExtra("liveTimes", System.currentTimeMillis() - startTime);
                jumpToActivity(intent);
            });
            exitDialog.hide();
        }
    }

    /*pause状态  本界面的弹框不算*/
    private boolean isRealPause() {
        if (fragmentLayer == null) return false;
        return !fragmentLayer.isDialogShowing();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isRealPause() && !isShare) {
            if (mPublisher != null) {
                mPublisher.mute(true);
            }
            if (isClosed) {
                sendCloseMessage();
            } else {
                sendLeaveMessage();
                isRealPause = true;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mPublisher != null && isRealPause && !isShare) {
            mPublisher.mute(false);
            sendReBackMessage();
            isRealPause = false;
        }
    }

    private void sendLeaveMessage() {
        String msg = "主播暂时离开了一下，马上回来";
        fragmentLayer.sendNotifyMessage(msg);
    }

    private void sendCloseMessage() {
        String msg = "主播已下播,您可以继续在直播间进行游戏";
        fragmentLayer.sendNotifyMessage(msg);
    }

    private boolean isRealPause;

    private void sendReBackMessage() {
        String msg = "主播回来啦，直播即将恢复";
        fragmentLayer.sendNotifyMessage(msg);
    }

    private void share(int index) {
        switch (index) {
            case 0:
                ShareUtils.shareToSocial(mActivity, SHARE_MEDIA.SINA, info);
                break;
            case 1:
                ShareUtils.shareToSocial(mActivity, SHARE_MEDIA.WEIXIN, info);
                break;
            case 2:
                ShareUtils.shareToSocial(mActivity, SHARE_MEDIA.WEIXIN_CIRCLE, info);
                break;
            case 3:
                ShareUtils.shareToSocial(mActivity, SHARE_MEDIA.QQ, info);
                break;
        }

    }

    private void setSelected(int index) {
        ivSina.setImageResource(index == 0 ? R.drawable.icon_sina_selected : R.drawable.icon_sina);
        ivWeixin.setImageResource(index == 1 ? R.drawable.icon_weixin_selected : R.drawable.icon_weixin);
        ivWeixinCircle.setImageResource(index == 2 ? R.drawable.icon_friend_selected : R.drawable.icon_friend);
        ivQQ.setImageResource(index == 3 ? R.drawable.icon_qq_selected : R.drawable.icon_qq);
    }

    @Override
    public <T> void update(ObserverableType key, T data) {
        if (rtmpUrl == null) {
            showSnackbar(getRootView(mActivity), "开播失败，请联系客服MM", 0);
        } else {
            mHandler.postDelayed(() -> {
                if (!isShare) {
                    startLive();
                } else {
                    isShare = false;
                }
            }, 1000);
        }
    }

    public int getGameId() {
        return gameID;
    }

    public void setGameID(int gameID) {
        this.gameID = gameID;
    }

    private void showDialog() {
        if (dialog == null) {
            View view = LayoutInflater.from(mActivity).inflate(R.layout.layout_choose_dialog, null);
            dialog = new CustomDialog(mActivity, view);
            view.findViewById(R.id.btnCancel).setVisibility(View.GONE);
            TextView tvTitle = (TextView) view.findViewById(R.id.tvTitle);
            tvTitle.setText("禁播提示");
            TextView tvContent = (TextView) view.findViewById(R.id.tvContent);
            tvContent.setText("由于您之前的违规行为，已被禁播\n如有疑问，请联系客服QQ群624846111");
            TextView tvSure = (TextView) view.findViewById(R.id.btnSure);
            tvSure.setText("确定");
            tvSure.setOnClickListener((v) -> {
                dialog.dismiss();
            });
            dialog.setCancelable(false);
            dialog.setCanceledOnTouchOutside(false);
        } else {
            dialog.show();
        }
    }


    public boolean isShare() {
        return isShare;
    }

    public void setShare(boolean share) {
        isShare = share;
    }

    @Override
    public void onPublishStart() {
    }

    @Override
    public void onPublishStop() {
    }

    @Override
    public void onPublishException() {
        Log.e(TAG, "onHandleException");
        if (mPublisher != null) {
            mPublisher.stopPublish();
            mPublisher = null;
        }
        jumpToActivity(LiveEndActivity.class);
        finish();
    }

    public void stop() {
        stopLive();
        finish();
    }

    private static class StopLiveReceiver extends BroadcastReceiver {
        private WeakReference<PlayLiveRoomActivity> weakReference;

        public StopLiveReceiver(PlayLiveRoomActivity activity) {
            this.weakReference = new WeakReference<PlayLiveRoomActivity>(activity);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (weakReference.get() != null) {
                weakReference.get().stopLive();
                weakReference.get().finish();
                weakReference.get().jumpToActivity(LiveEndActivity.class);
            }
        }
    }
}
